package com.quanshu.exchange.support.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;

import com.hyphenate.chat.EMConversation;
import com.hyphenate.util.HanziToPinyin;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.chat.ChatConstant;
import com.quanshu.exchange.support.entity.CountryEntity;
import com.quanshu.exchange.support.entity.StateNationalEntity;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.entity.tmp.TmpCountryInfo;
import com.quanshu.exchange.ui.base.MyApplication;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by jye on 2017/11/27.
 */

public class AppUtils {

    public static int getVersionCode(Context context) {

        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static String getVersionName(Context context) {

        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * check the application process name if process name is not qualified, then we think it is a service process and we will not init SDK
     *
     * @param pID
     * @return
     */
    public static String getProcessName(Context appContext, int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = appContext.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
                    // Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
                    // info.processName +"  Label: "+c.toString());
                    // processName = c.toString();
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }

    /**
     * 获取应用程序名称
     */
    public static String getAppName(Context context) {
        // 获取应用程序名称
        int labelRes = context.getApplicationInfo().labelRes;
        return context.getResources().getString(labelRes);
    }

    // 参数加密
    public static String getSignParams(String... arrays) {
        if (arrays == null || arrays.length < 1) {
            return "";
        }
        String[] arr = arrays.clone();
        Arrays.sort(arr);
        StringBuffer sb = new StringBuffer();
        for (String s : arr) {
            sb.append(s);
        }
        sb.append("quanshu");
        String str = sb.toString();
        return Md5Encrypt.md5(str);
    }

    public static ArrayList<TmpCountryInfo> formatData(CountryEntity countryBean) {
        ArrayList<TmpCountryInfo> list = new ArrayList<>();
        TmpCountryInfo tmp;
        if (countryBean != null) {
            if (!TextUtils.isEmpty(countryBean.getCN())) {
                tmp = new TmpCountryInfo();
                tmp.setCountryId("CN");
                tmp.setCountryName_CN(countryBean.getCN());
                list.add(tmp);
            }
            if (!TextUtils.isEmpty(countryBean.getHK())) {
                tmp = new TmpCountryInfo();
                tmp.setCountryId("HK");
                tmp.setCountryName_CN(countryBean.getHK());
                list.add(tmp);
            }
            if (!TextUtils.isEmpty(countryBean.getID())) {
                tmp = new TmpCountryInfo();
                tmp.setCountryId("ID");
                tmp.setCountryName_CN(countryBean.getID());
                list.add(tmp);
            }
            if (!TextUtils.isEmpty(countryBean.getKH())) {
                tmp = new TmpCountryInfo();
                tmp.setCountryId("KH");
                tmp.setCountryName_CN(countryBean.getKH());
                list.add(tmp);
            }
            if (!TextUtils.isEmpty(countryBean.getMY())) {
                tmp = new TmpCountryInfo();
                tmp.setCountryId("MY");
                tmp.setCountryName_CN(countryBean.getMY());
                list.add(tmp);
            }
            if (!TextUtils.isEmpty(countryBean.getSG())) {
                tmp = new TmpCountryInfo();
                tmp.setCountryId("SG");
                tmp.setCountryName_CN(countryBean.getSG());
                list.add(tmp);
            }
            if (!TextUtils.isEmpty(countryBean.getTH())) {
                tmp = new TmpCountryInfo();
                tmp.setCountryId("TH");
                tmp.setCountryName_CN(countryBean.getTH());
                list.add(tmp);
            }
            if (!TextUtils.isEmpty(countryBean.getTW())) {
                tmp = new TmpCountryInfo();
                tmp.setCountryId("TW");
                tmp.setCountryName_CN(countryBean.getTW());
                list.add(tmp);
            }
            if (!TextUtils.isEmpty(countryBean.getUS())) {
                tmp = new TmpCountryInfo();
                tmp.setCountryId("US");
                tmp.setCountryName_CN(countryBean.getUS());
                list.add(tmp);
            }
            if (!TextUtils.isEmpty(countryBean.getVN())) {
                tmp = new TmpCountryInfo();
                tmp.setCountryId("VN");
                tmp.setCountryName_CN(countryBean.getVN());
                list.add(tmp);
            }
        }
        return list;
    }

    public static ArrayList<StateNationalEntity> stateData() {

        ArrayList<StateNationalEntity> list = new ArrayList<>();
        StateNationalEntity stateNationalEntity = new StateNationalEntity();
        stateNationalEntity.setFlag_id(86);
        stateNationalEntity.setFlag_national(R.drawable.flag_cn);
        stateNationalEntity.setFlag_name("中国");
        list.add(stateNationalEntity);

        stateNationalEntity = new StateNationalEntity();
        stateNationalEntity.setFlag_id(86);
        stateNationalEntity.setFlag_national(R.drawable.flag_hk);
        stateNationalEntity.setFlag_name("香港");
        list.add(stateNationalEntity);

        stateNationalEntity = new StateNationalEntity();
        stateNationalEntity.setFlag_id(62);
        stateNationalEntity.setFlag_national(R.drawable.flag_id);
        stateNationalEntity.setFlag_name("印度尼西亚");
        list.add(stateNationalEntity);

        stateNationalEntity = new StateNationalEntity();
        stateNationalEntity.setFlag_id(855);
        stateNationalEntity.setFlag_national(R.drawable.flag_kh);
        stateNationalEntity.setFlag_name("柬埔寨");
        list.add(stateNationalEntity);

        stateNationalEntity = new StateNationalEntity();
        stateNationalEntity.setFlag_id(60);
        stateNationalEntity.setFlag_national(R.drawable.flag_my);
        stateNationalEntity.setFlag_name("马来西亚");
        list.add(stateNationalEntity);

        stateNationalEntity = new StateNationalEntity();
        stateNationalEntity.setFlag_id(65);
        stateNationalEntity.setFlag_national(R.drawable.flag_sg);
        stateNationalEntity.setFlag_name("新加坡");
        list.add(stateNationalEntity);

        stateNationalEntity = new StateNationalEntity();
        stateNationalEntity.setFlag_id(66);
        stateNationalEntity.setFlag_national(R.drawable.flag_th);
        stateNationalEntity.setFlag_name("泰国");
        list.add(stateNationalEntity);

        stateNationalEntity = new StateNationalEntity();
        stateNationalEntity.setFlag_id(86);
        stateNationalEntity.setFlag_national(R.drawable.flag_tw);
        stateNationalEntity.setFlag_name("台湾");
        list.add(stateNationalEntity);

        stateNationalEntity = new StateNationalEntity();
        stateNationalEntity.setFlag_id(001);
        stateNationalEntity.setFlag_national(R.drawable.flag_us);
        stateNationalEntity.setFlag_name("美国");
        list.add(stateNationalEntity);

        stateNationalEntity = new StateNationalEntity();
        stateNationalEntity.setFlag_id(84);
        stateNationalEntity.setFlag_national(R.drawable.flag_vn);
        stateNationalEntity.setFlag_name("越南");
        list.add(stateNationalEntity);


        return list;
    }

    /**
     * change the chat type to EMConversationType
     *
     * @param chatType
     * @return
     */
    public static EMConversation.EMConversationType getConversationType(int chatType) {
        if (chatType == ChatConstant.CHAT_TYPE_SINGLE) {
            return EMConversation.EMConversationType.Chat;
        } else if (chatType == ChatConstant.CHAT_TYPE_GROUP) {
            return EMConversation.EMConversationType.GroupChat;
        } else {
            return EMConversation.EMConversationType.ChatRoom;
        }
    }

    public static String getUserInitialLetter(UserEntity user) {

        if (!TextUtils.isEmpty(user.getRemark())) {
            return getInitialLetter(user.getRemark());

        } else if (!TextUtils.isEmpty(user.getNickname())) {
            return getInitialLetter(user.getNickname());

        } else if (!TextUtils.isEmpty(user.getMemberid())) {

            return getInitialLetter(user.getMemberid());
        } else {
            return "#";
        }
    }

    public static String getUserName(UserEntity user) {
        if (!TextUtils.isEmpty(user.getRemark())) {
            return user.getRemark();
        } else if (!TextUtils.isEmpty(user.getNickname())) {
            return user.getNickname();
        } else {
            return user.getMemberid();
        }
    }

    public static String getInitialLetter(String name) {
        String defaultLetter = "#";
        if (TextUtils.isEmpty(name)) {
            return defaultLetter;
        }
        char char0 = name.toLowerCase().charAt(0);
        if (Character.isDigit(char0)) {
            return defaultLetter;
        }
        ArrayList<HanziToPinyin.Token> l = HanziToPinyin.getInstance().get(name.substring(0, 1));
        if (l != null && l.size() > 0 && l.get(0).target.length() > 0) {
            HanziToPinyin.Token token = l.get(0);
            String letter = token.target.substring(0, 1).toUpperCase();
            char c = letter.charAt(0);
            if (c < 'A' || c > 'Z') {
                return defaultLetter;
            }
            return letter;
        }
        return defaultLetter;
    }

    public static boolean inRangeOfView(View view, MotionEvent ev) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int x = location[0];
        int y = location[1];
        if (ev.getX() < x || ev.getX() > (x + view.getWidth()) || ev.getY() < y || ev.getY() > (y + view.getHeight())) {
            return false;
        }
        return true;
    }

    public static String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public static void sortDataByPinYin(List<UserEntity> userList) {

        // sorting
        Collections.sort(userList, (user1, user2) -> {
            String user1Letter = AppUtils.getUserInitialLetter(user1);
            String user2Letter = AppUtils.getUserInitialLetter(user2);
            if (user1Letter.equals(user2Letter)) {
                return getInitialLetter(getUserName(user1)).compareTo(getUserName(user2));
            } else {
                return user1Letter.compareTo(user2Letter);
            }
        });
    }

    public static Map<String, ArrayList> sort(ArrayList list) {
        TreeMap tm = new TreeMap();
        for (int i = 0; i < list.size(); i++) {
            UserEntity s = (UserEntity) list.get(i);
            if (tm.containsKey(s.getLabel_id())) {//
                ArrayList l11 = (ArrayList) tm.get(s.getLabel_id());
                l11.add(s);
            } else {
                ArrayList tem = new ArrayList();
                tem.add(s);
                tm.put(s.getLabel_id(), tem);
            }
        }
        return tm;
    }

    public static File getFileByUri(Uri uri, Context context) {
        String path = null;
        if ("file".equals(uri.getScheme())) {
            path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = context.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA}, buff.toString(), null, null);
                int index = 0;
                int dataIdx = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    index = cur.getInt(index);
                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    path = cur.getString(dataIdx);
                }
                cur.close();
                if (index == 0) {
                } else {
                    Uri u = Uri.parse("content://media/external/images/media/" + index);
                    System.out.println("temp uri is :" + u);
                }
            }
            if (path != null) {
                return new File(path);
            }
        } else if ("content".equals(uri.getScheme())) {
            // 4.2.2以后
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
            cursor.close();

            return new File(path);
        } else {
//            Log.i(TAG, "Uri Scheme:" + uri.getScheme());
        }
        return null;
    }


    /**
     * 启动裁剪
     *
     * @param activity     上下文
     * @param sourceUir    需要裁剪图片的Uri
     * @param aspectRatioX 裁剪图片宽高比
     * @param aspectRatioY 裁剪图片宽高比
     * @return
     */
    public static void startUCrop(Activity activity, Uri sourceUir, float aspectRatioX, float aspectRatioY) {
        //裁剪后保存到文件中
        Uri destinationUri = Uri.fromFile(new File(activity.getCacheDir(), System.currentTimeMillis() + ".jpg"));
        //初始化，第一个参数：需要裁剪的图片；第二个参数：裁剪后图片
        UCrop uCrop = UCrop.of(sourceUir, destinationUri);
        //初始化UCrop配置
        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(activity, R.color.black));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(activity, R.color.black));
        //是否能调整裁剪框
        //是否隐藏底部容器，默认显示
        options.setHideBottomControls(true);
//        options.setFreeStyleCropEnabled(true);
        uCrop.withOptions(options);
        //设置裁剪图片的宽高比，比如16：9（设置后就不能选择其他比例了、选择面板就不会出现了）
        uCrop.withAspectRatio(aspectRatioX, aspectRatioY);
        uCrop.start(activity);
    }

    /**
     * 启动裁剪
     *
     * @param sourceUir    需要裁剪图片的Uri
     * @param aspectRatioX 裁剪图片宽高比
     * @param aspectRatioY 裁剪图片宽高比
     * @return
     */
    public static void startFragmentUCrop(Context context, Fragment fragment, Uri sourceUir, float aspectRatioX, float aspectRatioY) {
        //裁剪后保存到文件中
        Uri destinationUri = Uri.fromFile(new File(context.getCacheDir(), System.currentTimeMillis() + ".jpg"));
        //初始化，第一个参数：需要裁剪的图片；第二个参数：裁剪后图片
        UCrop uCrop = UCrop.of(sourceUir, destinationUri);
        //初始化UCrop配置
        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(context, R.color.black));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(context, R.color.black));
        //是否能调整裁剪框
        //是否隐藏底部容器，默认显示
        options.setHideBottomControls(true);
//        options.setFreeStyleCropEnabled(true);
        uCrop.withOptions(options);
        //设置裁剪图片的宽高比，比如16：9（设置后就不能选择其他比例了、选择面板就不会出现了）
        uCrop.withAspectRatio(aspectRatioX, aspectRatioY);
        uCrop.start(context, fragment);
    }


    public static List<Camera.Size> getResolutionList(Camera camera) {
        Camera.Parameters parameters = camera.getParameters();
        return parameters.getSupportedPreviewSizes();
    }


    // 获取视频缩略图
    public static Bitmap getVideoThumbnail(String filePath) {
        Bitmap b = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            b = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        return b;
    }


    public static String saveBitmap2File(Context context, Bitmap bitmap) {

        // 创建File对象，用于存储拍照后的图片
        File outputImage = new File(context.getExternalCacheDir(), System.currentTimeMillis() + "thumb.jpg");
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(outputImage);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        } catch (Exception e) {
            return "create_bitmap_error";
        }
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputImage.getAbsolutePath();
    }

    public static Bitmap getImage(String Url) throws Exception {
        try {
            URL url = new URL(Url);
            String responseCode = url.openConnection().getHeaderField(0);
            if (responseCode.indexOf("200") < 0)
                throw new Exception("图片文件不存在或路径错误，错误代码：" + responseCode);
            return BitmapFactory.decodeStream(url.openStream());
        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }
    }

    public static Bitmap getBitmap(String path) throws IOException {
        URL fileUrl = null;
        Bitmap bitmap = null;
        try {
            fileUrl = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) fileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * Bitmap -> byte[]
     *
     * @param sourceBitmap
     * @return
     */
    public static byte[] getBitmapBytes(Bitmap sourceBitmap) {
        Bitmap bitmap = Bitmap.createScaledBitmap(sourceBitmap, DensityUtil.dp2px(MyApplication.getInstance(), 80), DensityUtil.dp2px(MyApplication.getInstance(), 60), true);
        byte[] bytes = compressBitmap(bitmap, 30);
        sourceBitmap.recycle();
        bitmap.recycle();
        return bytes;
    }

    /**
     * 压缩图片到指定大小
     *
     * @param image
     * @param maxSize
     * @return
     */
    public static byte[] compressBitmap(Bitmap image, int maxSize) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > maxSize) { // 循环判断如果压缩后图片是否大于maxSize kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        return baos.toByteArray();
    }

}
